package com.imooc.miaosha.service;

import java.util.Date;

import com.imooc.miaosha.redis.OrderKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.imooc.miaosha.dao.OrderDao;
import com.imooc.miaosha.domain.MiaoshaOrder;
import com.imooc.miaosha.domain.MiaoshaUser;
import com.imooc.miaosha.domain.OrderInfo;
import com.imooc.miaosha.vo.MiaoshaGoodsVo;

@Service
public class OrderService {

    private final OrderDao orderDao;
    private final RedisService redisService;

    @Autowired
    public OrderService(OrderDao orderDao, RedisService redisService) {
        this.orderDao = orderDao;
        this.redisService = redisService;
    }

    public MiaoshaOrder getMiaoshaOrderByUserIdAndGoodsId(long userId, long goodsId) {
        //从缓存里面取订单数据
        return redisService.get(OrderKey.getMiaoshaOrderByUIdGId, "" + userId + "" + goodsId, MiaoshaOrder.class);
    }

    @Transactional
    public OrderInfo createOrder(MiaoshaUser user, MiaoshaGoodsVo goods) {
        //创建订单信息
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goods.getId());
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setGoodsPrice(goods.getMiaoshaPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setUserId(user.getId());
        orderDao.insert(orderInfo);
        //创建秒杀订单
        MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
        miaoshaOrder.setGoodsId(goods.getId());
        miaoshaOrder.setOrderId(orderInfo.getId());
        miaoshaOrder.setUserId(user.getId());
        //插入秒杀订单
        orderDao.insertMiaoshaOrder(miaoshaOrder);
        //插入redis的秒杀订单
        redisService.set(OrderKey.getMiaoshaOrderByUIdGId, "" + orderInfo.getUserId() + "" + orderInfo.getGoodsId(), miaoshaOrder);
        return orderInfo;
    }

    public OrderInfo getOrderInfoByUserIdAndOrderId(Long id, long orderId) {
        return orderDao.getOrderInfoByUserIdAndOrderId(id, orderId);
    }
}
